<template>
  <div class="hello">
    <h1>{{ msg }}</h1>
    <p>
      <input type="text" @keydown.enter="addFeature" />
      {{ FeaturesCount }}
    </p>
    <ul>
      <li v-for="feature in features" :key="feature.id">{{ feature.name }}</li>
    </ul>
  </div>
</template>

<script lang="ts">
import { Component, Prop, Vue, Watch, Emit } from 'vue-property-decorator';
import { Feature } from "@/types";
import { getFeatures } from "@/api/feature";

@Component
export default class HelloWorld extends Vue {
  // 1.data: 属性就是data
  features: Feature[] = []
  // 2.生命周期：如果和生命周期钩子同名，就是生命周期
  created() {
    getFeatures().then((res: { data: Feature[] }) => {
      this.features = res.data
    })
  }
  // 7. 事件派发：@Emit
  // 7.1 通知⽗类新增事件，若未指定事件名则函数名作为事件名（⽺⾁串形式）
  // 7.2 如果有返回值，则作为事件参数
  // 7.3 下面等同于 this.$emit('add-feature', feature)
  @Emit()
  // 3.methods：函数直接作为methods
  addFeature(e: KeyboardEvent) {
    const inp = e.target as HTMLInputElement;
    const feature = { id: this.features.length + 1, name: inp.value };
    this.features.push(feature);
    inp.value = "";
    return feature
  }
  // 4.计算属性：存取器用于计算属性
  get FeaturesCount() {
    return this.features.length
  }
  // 5. 变更监测：@Watch
  @Watch('features')
  onFeaturesChange(newVal: Feature[]) {
    console.log('onFeaturesChange', newVal)
  }
  // 6. 父组件传值：@Prop
  // 括号中的配置时给Vue的
  // 变量附近的配置时给ts
  // '!'：非空断言操作符
  @Prop({ type: String, required: true }) private msg!: string;
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
h3 {
  margin: 40px 0 0;
}
ul {
  list-style-type: none;
  padding: 0;
}
a {
  color: #42b983;
}
</style>
